<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>工作台</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div style="margin: 24px;" class="land_center">
      <!-- 图 -->
      <a-card>
        <a-row>
          <a-col :span="24">
            <a-tabs :animated="false" :tabBarGutter="16" :activeKey="a" @change="onChangetab">
              <a-tab-pane v-for="v in tabs" :key="v.key" :tab="v.title"></a-tab-pane>
              <template slot="tabBarExtraContent">
                <date-searcher @change="initDateSearch" />
              </template>
            </a-tabs>
          </a-col>
          <a-col :span="16">
            <h1 class="headTitle" style="padding-left:34px;">{{chart1Name}}</h1>
            <div id="bar1" style="height: 350px;"></div>
          </a-col>
          <a-col :span="8">
            <div style="height: 400px;">
              <h1 class="headTitle">司机排名</h1>
              <div class="rankBody" style="margin-right:24px;">
                <p class="ranking" v-for="(v, i) in data2" :key="i">
                  <span class="numberStyle">
                    <img v-if="i < 3" :src="nosPic[i]" />
                    <template v-else>
                      <span>{{i+1}}</span>
                    </template>
                  </span>
                  <span class="numberText">{{v.driverName}}</span>
                  <span class="numberPer">
                    <span
                      :style="{'display': 'inline-block', height: '22px', 'background': 'rgb(58, 161, 255)', 'width': getWidthPer(v) + '%'}"
                    ></span>
                  </span>
                  <span v-if="form1.type === 1" class="numberDesc">{{v.containerNumTotal}}个</span>
                  <span v-if="form1.type === 2" class="numberDesc">{{v.mileageTotal}}km</span>
                  <span v-if="form1.type === 3" class="numberDesc">{{v.profitTotal}}元</span>
                </p>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-card>

      <!-- 车辆动态监控 -->
      <a-card>
        <div class="card-title hasContent">
          车辆动态监控
          <a-button type="primary" ghost size="small" @click="refreshIt">
            <a-icon type="sync" />刷新
          </a-button>
          <a-input-search
            v-model="searchValue"
            placeholder="搜索车牌号"
            style="width: 200px; float:right;"
            @search="onSearch"
          ></a-input-search>
        </div>
        <div v-if="data3.length === 0" style="padding: 210px 0">
          <a-empty />
        </div>
        <a-carousel v-if="data3.length > 0" arrows dotsClass="slick-dotsExp">
          <div
            v-for="(v, i) in new Array(cartabs)"
            :key="i"
            class="carMonitor"
            style="padding:5px 24px;"
          >
            <a-row :gutter="[20, 15]">
              <a-col v-for="(v, j) in cars[i]" :key="j" :span="8">
                <div class="carItem">
                  <div>
                    <!--<img :src="carIcon"/>-->
                    <img src="../../../static/images/lyun.png" alt />
                    <p style="font-size:18px; margin-bottom:0px;">
                      <a
                        :href="`/landCenter/tractorManagement/${v.tractorId}`"
                        target="_blank"
                      >{{v.tractorNumber||'--'}}</a>
                      <a
                        :href="`/landCenter/railerManagement/${v.trailerId}`"
                        target="_blank"
                        v-if="v.trailerNumber"
                      >·{{v.trailerNumber}}</a>
                      <span v-if="v.isSelfOperation===1" class="selfFlag">自营</span>
                      <span v-if="v.isSelfOperation===0" class="selfFlag selfFlag1">外派</span>
                    </p>
                    <p style="color:rgba(0,0,0,0.65 )">
                      {{v.name}}
                      <span>·{{v.phone}}</span>
                    </p>
                  </div>
                  <ul class="orderList">
                    <li
                      v-for="(item, i) in v.orderList"
                      :key="i"
                      style="width:100%; overflow: hidden;"
                    >
                      <a
                        :href="`/landCenter/orderDispatch/${item.truckOrderId}`"
                        target="_blank"
                        style=" width:108px; display:block; float:left;"
                      >{{item.truckOrderCode}}</a>
                      <span
                        style=" width:42%; display:block; float:left; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;"
                      >{{opeTypeStr(item.opeType, item.emptyOrHeavy)}}</span>
                      <span style="float:right; font-size:12px; color:#999;">{{item.flowTime}}</span>
                    </li>
                  </ul>
                </div>
              </a-col>
            </a-row>
          </div>
        </a-carousel>
      </a-card>

      <a-row :gutter="20">
        <a-col :span="14">
          <!-- 提醒 -->
          <a-card>
            <a-tabs defaultActiveKey @change="initMessage">
              <a-tab-pane key tab="全部提醒"></a-tab-pane>
              <a-tab-pane :key="1" tab="车辆"></a-tab-pane>
              <a-tab-pane :key="2" tab="订单"></a-tab-pane>
            </a-tabs>
            <a-list
              item-layout="horizontal"
              :data-source="data4"
              :loading="loading"
              :pagination="pagination"
              style="margin:0 24px 16px 24px;"
            >
              <a-list-item slot="renderItem" slot-scope="item">
                <a-list-item-meta :description="item.createTime">
                  <template slot="title">
                    <strong>{{ item.title }}：</strong>
                    <template
                      v-if="item.type==='ORDER_ABNORMAL_PC' || item.type==='ORDER_EMPTYING_PC' || item.type === 'ORDER_SHIP_ANOMALOUS'"
                    >
                      {{getMessagePart(item)[0]}}
                      <a
                        style="color: #1890ff"
                        :href="`/landCenter/orderDispatch/${item.relId}`"
                        target="_blank"
                      >{{getMessagePart(item)[1]}}</a>
                      <template
                        v-if="item.type === 'ORDER_SHIP_ANOMALOUS'"
                      >{{getMessagePart(item)[2]}}</template>
                      <a-button
                        type="primary"
                        v-if="item.type==='ORDER_SHIP_ANOMALOUS'"
                        @click="readMessage(item.messageId)"
                      >好的，我知道了</a-button>
                    </template>
                    <template
                      v-else-if="item.type==='TRUCK_INSURANCE_TRACTOR'||item.type==='TRUCK_INSPECTION_TRACTOR'||item.type==='TRUCK_MAINTENANCE_TRACTOR'"
                    >
                      <a
                        style="color: #1890ff"
                        :href="`/landCenter/tractorManagement/${item.relId}`"
                        target="_blank"
                      >{{getMessagePart(item)[0]}}</a>
                      {{getMessagePart(item)[1]}}
                    </template>
                    <template
                      v-else-if="item.type==='TRUCK_INSURANCE_TRAILER'||item.type==='TRUCK_INSPECTION_TRAILER'||item.type==='TRUCK_MAINTENANCE_TRAILER'"
                    >
                      <a
                        style="color: #1890ff"
                        :href="`/landCenter/railerManagement/${item.relId}`"
                        target="_blank"
                      >{{getMessagePart(item)[0]}}</a>
                      {{getMessagePart(item)[1]}}
                    </template>
                    <template v-else-if="item.type==='PENALTY_AREA_REPORT_PC'">
                      {{getMessagePart(item)[0]}}
                      <a
                        style="color: #1890ff"
                        href="/landCenter/penaltyAreaAudit"
                        target="_blank"
                      >{{getMessagePart(item)[1]}}</a>
                    </template>
                  </template>

                  <a-avatar slot="avatar" :src="msgType(item.type)">
                    <!-- {{msgType(item.type)}} -->
                  </a-avatar>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-card>
        </a-col>

        <!-- 油信息 -->
        <a-col :span="10">
          <a-card>
            <a-tabs :defaultActiveKey="1" @change="initOilInfo">
              <a-tab-pane :key="1" tab="油量">
                <a-row>
                  <a-col :span="24">
                    <div id="liquidFill-oil-1" style="width:100%;height:260px"></div>
                  </a-col>
                </a-row>
                <a-row :gutter="[16]" style="margin-top:20px; margin-bottom:36px;">
                  <a-col :span="12">
                    <div id="liquidFill-oil-2" style="width:100%;height:160px"></div>
                  </a-col>
                  <a-col :span="12">
                    <div id="liquidFill-oil-3" style="width:100%;height:160px"></div>
                  </a-col>
                </a-row>
              </a-tab-pane>
              <a-tab-pane :key="2" tab="加油卡">
                <a-row style="height:476px; padding:0 24px;">
                  <a-col :span="24">
                    <a-table :columns="columns" :dataSource="data52" rowKey="cardNo"></a-table>
                  </a-col>
                </a-row>
              </a-tab-pane>
              <a-tab-pane :key="3" tab="ECT">
                <a-row style="height:476px; padding-top:15%;">
                  <a-col :span="24">
                    <div id="liquidFill-oil-4" style="width:100%;height:260px;"></div>
                  </a-col>
                </a-row>
              </a-tab-pane>
            </a-tabs>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import { queryWorkbenchStatistics, queryWorkbenchTruckList, queryWorkbenchOilStatistics, queryWorkbenchMessageList, readMessageInfo } from '@/api/landCenter'
// eslint-disable-next-line no-unused-vars
import echartsLiquidfill from 'echarts-liquidfill'
import DateSearcher from '@/components/DateSearch'
import 'echarts/lib/chart/bar'

import no1 from '@/../static/images/no1.png'
import no2 from '@/../static/images/no2.png'
import no3 from '@/../static/images/no3.png'
import carIcon from '@/../static/images/carIcon.png'

const tabs = [
  { key: 1, title: '箱量' },
  { key: 2, title: '里程数' },
  { key: 3, title: '毛利' }
]
const nosPic = [no1, no2, no3]

export default {
  data () {
    const columns = [
      {
        title: '卡号',
        dataIndex: 'cardNo',
        customRender: (text, record) => {
          if (parseFloat(record.amount) <= 1000) {
            return <div><a-icon type="exclamation-circle" style="color: #ff9900; margin-right: 5px;" />{text}</div>
          }
          return text
        }
      },
      {
        title: '余额(元)',
        dataIndex: 'amount'
      }
    ]
    return {
      a: 1,
      carIcon,
      tabs,
      nosPic,
      form1: {
        type: 1, // 1箱量 2里程数 3毛利
        dateType: 1, // 1按日 2按周 3按月 4按年
        time1: '', // 年月日
        time2: '' // 年月日
      },
      bar1: null,
      chart1Name: '',
      data1: {}, // 柱状图
      data2: [], // 司机排名
      monitors: [1], // 監控車輛，默认一个tab
      data3: [], // 监控车辆信息
      cartabs: 1,
      cars: [], // 分割后的二维数组
      searchValue: '',
      data4: [],
      loading: false,
      msgselType: '',
      pageNum: 1,
      pagination: null,
      columns,
      data51: {}, // 1油量 2加油卡 3ECT
      data52: [], // 1油量 2加油卡 3ECT
      data53: {} // 1油量 2加油卡 3ECT
    }
  },
  components: {
    [DateSearcher.name]: DateSearcher
  },
  computed: {
    typeKey () {
      return this.form1.type === 1 ? 'containerNumTotal' : (this.form1.type === 2 ? 'mileageTotal' : (this.form1.type === 3 ? 'profitTotal' : ''))
    }
  },
  created () {
    this.pagination = this.getPagination()
  },
  methods: {
    opeTypeStr (opeType, emptyOrHeavy) {
      const flow11 = emptyOrHeavy === 1 ? '-空箱' : (emptyOrHeavy === 2 ? '-重箱' : '')
      if (opeType === 0) return '生成订单'
      else if (opeType === 1) return '操作派单'
      else if (opeType === 2) return '调度接单'
      else if (opeType === 3) return '调度派单'
      else if (opeType === 4) return '完成订单-异常结束'
      else if (opeType === 5) return '作废'
      else if (opeType === 10) return '司机接单'
      else if (opeType === 11) return '开始订单-提箱离港' + flow11
      else if (opeType === 12) return '开始订单-空车离港' + flow11
      else if (opeType === 13) return '开始订单-套箱接单' + flow11
      else if (opeType === 14 || opeType === 15) return '到达门点'
      else if (opeType === 16 || opeType === 17) return '完成装卸'
      else if (opeType === 18) return '上传货运凭证'
      else if (opeType === 19) return '完成订单-到港'
      else if (opeType === 20) return '完成订单-套箱接单'
      else if (opeType === 21) return '异常处理-故障报警'
      else if (opeType === 22) return '异常处理-放空'
    },
    getWidthPer (v) {
      const t = this.data2[0][this.typeKey]
      return t ? Math.floor(v[this.typeKey] / t * 100) : 0
    },
    getMessagePart (item) {
      const msg = item.content
      const type = item.type
      let t1 = ''
      let t2 = ''
      let t3 = ''
      if (msg && type) {
        if (type === 'TRUCK_INSURANCE_TRACTOR' || type === 'TRUCK_INSURANCE_TRAILER' || type === 'TRUCK_INSPECTION_TRACTOR' || type === 'TRUCK_INSPECTION_TRAILER' || type === 'TRUCK_MAINTENANCE_TRACTOR' || type === 'TRUCK_MAINTENANCE_TRAILER') { //  即将到
          const index = msg.indexOf('即将')
          t1 = msg.substring(0, index)
          t2 = msg.substring(index)
        } else if (type === 'ORDER_ABNORMAL_PC' || type === 'ORDER_EMPTYING_PC') {
          // 公司编号为
          const index = msg.indexOf('公司编号为')
          t1 = msg.substring(0, index + 5)
          t2 = msg.substring(index + 5)
        } else if (type === 'PENALTY_AREA_REPORT_PC') {
          // 立即审核
          t2 = '立即审核'
          const index = msg.indexOf(t2)
          t1 = msg.substring(0, index)
        } else if (type === 'ORDER_SHIP_ANOMALOUS') {
          // 公司编号为
          const index = msg.indexOf('公司编号为')
          t1 = msg.substring(0, index + 5)
          const index2 = msg.indexOf('的订单被佳华异常结束')
          t2 = msg.substring(index + 5, index2)
          t3 = msg.substring(index2)
        }
      }
      return [t1, t2, t3]
    },
    onChangetab (key) {
      if (key === 3 && !this.$root._bc.queryGrossProfit) {
        this.$message.error('您无此权限！')
        return
      }
      this.a = key
      this.form1.type = key
      this.handleSearch1()
    },
    initDateSearch (dateType, dateStr) { // 获得搜索日期, dateStr: [startDateStr, endDateStr]
      this.form1.dateType = dateType
      this.form1.time1 = dateStr[0]
      this.form1.time2 = dateStr[1]
      this.handleSearch1()
    },
    handleSearch1 () {
      queryWorkbenchStatistics(this.form1).then(rsp => {
        this.data1 = rsp.data
        this.data2 = rsp.data.driverList

        this.chart1Name = this.form1.type === 1 ? `箱量 ${this.data1.containerNumTotal}个` : (this.form1.type === 2 ? `里程数 ${this.data1.mileageTotal}km` : (this.form1.type === 3 ? `毛利 ${this.data1.profitTotal}元` : ''))

        const dataList = rsp.data.dataList
        const list = dataList.map(v => v[this.typeKey])
        const option1 = {
          color: ['rgb(58, 161, 255)'],
          xAxis: {
            type: 'category',
            data: dataList.map(v => v.time)
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: list,
            type: 'bar'
          }]
        }
        this.bar1.setOption(option1)
        window.setTimeout(() => { this.bar1.resize() })
      })
    },
    // 车辆动态监控
    onSearch (value) {
      queryWorkbenchTruckList({
        truckNumber: value,
        pageNum: 1,
        pageSize: 999
      }).then(rsp => {
        this.data3 = rsp.data.list
        this.cartabs = Math.ceil(this.data3.length / 9)
        let cars = []
        let temp = []
        for (let i = 0; i < this.cartabs; i++) {
          for (let j = 0; j < 9; j++) {
            if (this.data3[j + 9 * i]) {
              temp.push(this.data3[j + 9 * i])
            }
          }
          cars.push([...temp])
          temp = []
        }
        this.cars = cars
      })
    },
    refreshIt () {
      this.searchValue = ''
      this.onSearch()
    },
    // 提醒
    getPagination (data) {
      const pages = data ? data.pages : 0
      return {
        current: this.pageNum,
        pageSize: 10,
        total: data ? data.total : 0,
        showTotal: total => `共${total}条记录 第${this.pageNum}/${pages}页`,
        onChange: pageNum => {
          this.pageNum = pageNum
          this.searchMsg()
        }
      }
    },
    initMessage (k = '') {
      this.msgselType = k
      this.pageNum = 1
      this.loading = true
      queryWorkbenchMessageList({ type: k, pageNum: this.pageNum, pageSize: 10 }).then(rsp => {
        this.loading = false
        this.data4 = rsp.data.list
        this.pagination = this.getPagination(rsp.data)
      }).catch(() => { this.loading = false })
    },
    searchMsg () {
      this.loading = true
      queryWorkbenchMessageList({ type: this.msgselType, pageNum: this.pageNum, pageSize: 10 }).then(rsp => {
        this.loading = false
        this.data4 = rsp.data.list
        this.pagination = this.getPagination(rsp.data)
      }).catch(() => { this.loading = false })
    },
    msgType (t) {
      if (t === 'PENALTY_AREA_REPORT_PC') return '/static/images/jin.png'
      else if (t === 'ORDER_EMPTYING_PC') return '/static/images/kong.png'
      else if (t === 'ORDER_ABNORMAL_PC') return '/static/images/xiu.png'
      else if (t === 'ORDER_SHIP_ANOMALOUS') return '/static/images/yic.png'
      else if (t === 'TRUCK_MAINTENANCE_TRACTOR' || t === 'TRUCK_MAINTENANCE_TRAILER') return '/static/images/by.png'
      else if (t === 'TRUCK_INSPECTION_TRACTOR' || t === 'TRUCK_INSPECTION_TRAILER') return '/static/images/nj.png'
      else if (t === 'TRUCK_INSURANCE_TRACTOR' || t === 'TRUCK_INSURANCE_TRAILER') return '/static/images/bx.png'
      else return '?'
    },
    initOilInfo (key = 1) {
      queryWorkbenchOilStatistics({ type: key }).then(rsp => {
        this[`data5${key}`] = rsp.data
        if (key === 1) {
          this.liquidFill(1, this.data51.totalRemainingOil, '总剩余油量(L)')
          this.liquidFill(2, this.data51.remainingOil, '剩余柴油量(L)')
          this.liquidFill(3, this.data51.truckRemainingOil, '车辆剩余油量(L)')
        } else if (key === 3) {
          this.liquidFill(4, this.data53.amount, 'ETC余额(元)')
        }
      })
    },
    liquidFill (key, data, text) {
      let liquid = this.$echarts.init(
        document.getElementById('liquidFill-oil-' + key)
      )
      let result
      if (key === 1 || key === 2 || key === 3) { // 油量
        if (key === 2 && data < 20 * 1176) {
          result = 0.2
        } else {
          result = 0.5
        }
      } else { // ETC
        if (data >= 10000) {
          result = 0.5
        } else {
          result = 0.2
        }
      }

      liquid.setOption({
        series: [
          {
            type: 'liquidFill',
            data: [result],
            radius: '95%',
            backgroundStyle: {
              color: '#fff',
              shadowColor: '#fff',
              shadowBlur: 0
            },
            itemStyle: {
              normal: {
                shadowBlur: 0
              }
            },
            outline: {
              show: true,
              borderDistance: 5,
              itemStyle: {
                borderColor: result === 0.5 ? '#1890FF' : '#f5222d', // 边框的颜色
                borderWidth: 2
              }
            },
            color: result === 0.5 ? ['#1890FF'] : ['#f5222d'],
            label: {
              position: ['50%', '50%'],
              formatter: function (param) {
                return `${data}\n${text}`
              },
              fontSize: 14,
              color: '#666'
            }
          }
        ]
      })
      window.addEventListener('resize', () => {
        liquid.resize()
      })
    },
    readMessage (messageId) {
      readMessageInfo({ messageId }).then(rsp => {
        queryWorkbenchMessageList({ type: this.msgselType, pageNum: this.pageNum, pageSize: 10 }).then(rsp => {
          this.loading = false
          this.data4 = rsp.data.list
          this.pagination = this.getPagination(rsp.data)
        }).catch(() => { this.loading = false })
      })
    }
  },
  mounted () {
    this.$nextTick(() => {
      // part 1
      this.bar1 = this.$echarts.init(document.getElementById('bar1'))
      window.addEventListener('resize', () => {
        this.bar1.resize()
      })
      this.handleSearch1()

      // part 2
      this.onSearch()

      // part3
      this.initMessage()

      // part 4
      this.initOilInfo()
    })
  }
}
</script>

<style lang="less" scoped>
.ant-card {
  position: relative;
  margin-bottom: 24px;
  border: none;
  .cardEdit {
    position: absolute;
    right: 24px;
    top: 24px;
    z-index: 2;
  }
  .card-title {
    position: relative;
    padding-left: 16px;
    font-size: 18px;
    line-height: 1;
    color: #000;
    &:before {
      content: '';
      width: 5px;
      height: 18px;
      background: #1890ff;
      border-radius: 4px;
      position: absolute;
      left: 0;
      top: 2.5px;
    }
  }
  .hasContent {
    margin: 16px 24px;
  }
}
.headTitle {
  font-weight: bold;
  height: 50px;
  line-height: 30px;
  margin: 0;
}
.rankBody {
  height: 320px;
  overflow: auto;
  .ranking {
    margin: 5px 0 15px 0;
    overflow: hidden;
    .numberStyle {
      display: block;
      float: left;
      width: 30px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      margin-right: 10px;
    }

    .numberText {
      display: block;
      float: left;
      width: 80px;
      height: 30px;
      line-height: 30px;
      overflow: hidden;
    }

    .numberPer {
      display: block;
      float: left;
      width: 40%;
      height: 22px;
      padding: 4px 0;
    }

    .numberDesc {
      display: block;
      float: left;
      text-indent: 5px;
      height: 30px;
      line-height: 30px;
    }
  }
}
</style>

<style lang="less" scoped>
/deep/ .ant-carousel {
  .slick-dotsExp {
    button {
      background: #188fff9f;
    }

    .slick-active button {
      background: #1890ff;
    }
  }
  .carMonitor {
    height: 450px;
    overflow: hidden;

    .carItem {
      background: #f2f6fc;
      border-radius: 4px;
      padding: 15px;
      height: 130px;

      img {
        float: left;
        width: 36px;
        height: 36px;
        margin-right: 10px;
      }

      .selfFlag {
        color: #52c41a;
        border: 1px solid #b7eb8f;
        background: #f6ffed;
        font-size: 12px;
        line-height: 16px;
        padding: 1px 7px;
        border-radius: 2px;
        -moz-border-radius: 2px;
        -ms-border-radius: 2px;
        -o-border-radius: 2px;
        -webkit-border-radius: 2px;
      }
      .selfFlag1 {
        color: #faad14;
        border: 1px solid #ffe58f;
        background: #fffbe6;
      }
    }
  }
}
</style>
<style>
.land_center .ant-card-body {
  padding: 0;
}
.land_center .ant-tabs-top-bar {
  padding: 0px 24px;
}
.land_center .ant-tabs-nav .ant-tabs-tab {
  padding: 17.5px 16px;
}
.land_center .ant-tabs-extra-content {
  padding: 5px 20px 5px 0;
}
.land_center .ant-spin-nested-loading {
  height: 404px;
  overflow-y: scroll;
}
</style>
<style lang="less" scoped>
.land_center {
  /deep/ .ant-tabs-bar {
    margin: 0 !important;
    padding: 0 !important;
    border-bottom: 1px solid #e8e8e8 !important;
  }
  /deep/ .ant-tabs-tab {
    padding: 17.5px 24px !important;
  }
}
</style>
